package rehab.tutor.androidclient.service;

import java.io.IOException;

import org.json.JSONObject;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;

import rehab.tutor.androidclient.StartActivity;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class OauthTokenValidatorService extends Service {

	protected static String TAG = "OauthTokenValidatorService";
	
	final String AUTH_TOKEN_TYPE = "oauth2:https://www.googleapis.com/auth/userinfo.email";
	AccountManager accountManager = AccountManager.get(StartActivity.getInstance());
	
	public static String GOOGLE_ACCOUNT_EMAIL; 
	public static String GOOGLE_ACCOUNT_TOKEN;
	public static boolean GOOGLE_ACCOUNT_TOKEN_IS_VALID;
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	public static void updareUserToken(Activity activity) throws OperationCanceledException, AuthenticatorException, IOException
	{
		String AUTH_TOKEN_TYPE = "oauth2:https://www.googleapis.com/auth/userinfo.email";
		
		AccountManager accountManager = AccountManager.get(StartActivity.getInstance());
		accountManager.invalidateAuthToken("com.google", GOOGLE_ACCOUNT_TOKEN);								

		Account[] accounts = accountManager.getAccountsByType("com.google");
    	AccountManagerFuture<Bundle> amf = accountManager.getAuthToken(accounts[0], AUTH_TOKEN_TYPE, null, activity, null, null); 

    	Bundle bundle = amf.getResult();
		GOOGLE_ACCOUNT_EMAIL = (String) bundle.get(AccountManager.KEY_ACCOUNT_NAME);
		GOOGLE_ACCOUNT_TOKEN = bundle.getString(AccountManager.KEY_AUTHTOKEN);
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		
        new AsyncTask<String, String, String[]>(){

			@Override
			protected String[] doInBackground(String... params) {
				
	        	Log.i(TAG, "Started");

				while(true)
				{
					GOOGLE_ACCOUNT_TOKEN_IS_VALID = false;
					
					while(!GOOGLE_ACCOUNT_TOKEN_IS_VALID)
					{
					
						try{
							if(GOOGLE_ACCOUNT_TOKEN == null)
								this.getUserTokenAndUpdateAppValues(StartActivity.getInstance());
	
							if(this.isTokenValid())
							{
								GOOGLE_ACCOUNT_TOKEN_IS_VALID = true;
								
					        	Log.i(TAG, "Token is Valid: App logged");
							} else {
					        	Log.i(TAG, "Token is NOT Valid: Invalidate Token and Request for a new one");
					        	
								accountManager.invalidateAuthToken("com.google", GOOGLE_ACCOUNT_TOKEN);
								this.getUserTokenAndUpdateAppValues(StartActivity.getInstance());
							}

						} catch (Exception e){ 
				        	Log.e(TAG, "Request Token Error: sleep for 30 seconds");

				        	try {
								Thread.sleep(30*1000);
							} catch (InterruptedException e1) {
								e1.printStackTrace();
							}
						}
					}
					
	                // Have a rest for 15 minutes
		        	Log.i(TAG, "sleep for 5 minutes");
					try {
						Thread.sleep(5*60*1000);
					} catch (InterruptedException e) {}
				}
			}

		    public void getUserTokenAndUpdateAppValues(Activity activity) throws OperationCanceledException, AuthenticatorException, IOException 
		    {
				Account[] accounts = accountManager.getAccountsByType("com.google");
				
		    	AccountManagerFuture<Bundle> amf = accountManager.getAuthToken(accounts[0], AUTH_TOKEN_TYPE, null, activity, null, null); 

		    	Bundle bundle = amf.getResult();

				GOOGLE_ACCOUNT_EMAIL = (String) bundle.get(AccountManager.KEY_ACCOUNT_NAME);
				GOOGLE_ACCOUNT_TOKEN = bundle.getString(AccountManager.KEY_AUTHTOKEN);
		    }
		    
		    public boolean isTokenValid()
		    {
				ClientResource clientResource = new ClientResource(
						"https://www.googleapis.com/oauth2/v1/tokeninfo?access_token="
						+ GOOGLE_ACCOUNT_TOKEN);
				
				try {
					/** LA PARTE CHE VEDI QUI IN BASSO UTILIZZA RESTLET **/
					Representation rep = clientResource.get();
					JsonRepresentation json = new JsonRepresentation(rep);
					JSONObject object = json.getJsonObject();
					String user = (String) object.get("email");
					if (user == null)
						return false;
					else 
						return true;
					
				} catch (Exception e) { 
					return false; }	
		    }
		    
        }.execute("");
	}
}
